package goredis

import (
	"context"
	"fmt"
	"gitee.com/masaichi/mredis/mstruct"
	"github.com/go-redis/redis/v8"
	"log"
	"sync"
)

var redisClient *redis.Client
var redisClientOnce sync.Once //单例

func Redis(config mstruct.MCacheConfig) *redis.Client {
	addr := fmt.Sprintf("%s:%d", config.Host, config.Port)
	redisClientOnce.Do(func() {
		redisClient = redis.NewClient(&redis.Options{
			Addr:     addr,
			Password: config.Password, // no password set
			DB:       config.DB,       // use default DB

			PoolSize:     15, //连接池数量
			MinIdleConns: 10, //最小等待链接数
		})
		//测试是否连接正常
		pong, err := redisClient.Ping(context.Background()).Result()
		if err != nil {
			log.Fatal(fmt.Errorf("connect error:%s", err))
		}
		log.Println(pong)
	})

	return redisClient
}
